package com.gitee.huanminabc.utils_common.obj.reflect;

import java.lang.reflect.Field;

/**
 * @author huanmin
 * @date 2024/1/24
 */
public class EntityFieldsClear {

    /**
     * 清除非排除字段的所有字段值为null的字段, 包装类型设置为null,基本数据类型设置为默认值
     * @param obj 对象
     * @param excludeFields 需要排除的字段
     */

    public static void clearFieldsNull(Object obj, String... excludeFields) {
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        bak:
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            if (excludeFields != null) {
                for (String excludeField : excludeFields) {
                    //过滤serialVersionUID
                    if ("serialVersionUID".equals(name)) {
                        continue bak;
                    }
                    if (excludeField.equals(name)) {
                        continue bak;
                    }
                }
            }
            try {
                Object o = declaredField.get(obj);
                if (o != null) {
                   //判断非基本数据类型
                    if (!declaredField.getType().isPrimitive()) {
                        declaredField.set(obj, null);
                    } else {
                        declaredField.set(obj, getDefaultValue(declaredField.getType()));
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    private static Object getDefaultValue(Class<?> type) {
        if (type == int.class) {
            return 0;
        } else if (type == long.class) {
            return 0L;
        } else if (type == double.class) {
            return 0.0;
        } else if (type == float.class) {
            return 0.0f;
        } else if (type == boolean.class) {
            return false;
        } else if (type == char.class) {
            return '\u0000';
        } else if (type == byte.class) {
            return (byte) 0;
        } else if (type == short.class) {
            return (short) 0;
        } else {
            return null;
        }
    }


}
